package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author Guoyh
 * @since 2022-08-21
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveDish(dishDto);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page pageInfo = dishService.selectByPageAndCondition(page, pageSize, name);
        return R.success(pageInfo);
    }

    @GetMapping("/{id}")
    public R<DishDto> showInfo(@PathVariable long id) {
        DishDto dishDto = dishService.selectById(id);
        return R.success(dishDto);
    }


    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {

        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        dishService.updateDish(dishDto);
        return R.success("修改成功");
    }


    @PostMapping("/status/{flag}")
    public R<String> updateStatus(@PathVariable int flag, @RequestParam List<Long> ids) {
        log.info("{}", ids);
        dishService.updateStatus(flag, ids);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;

        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);


        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(dish.getName() != null, Dish::getName, dish.getName());
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishes = dishService.list(queryWrapper);

        List<DishDto> list = new ArrayList<>();

        dishes.forEach(
                new Consumer<Dish>() {
                    @Override
                    public void accept(Dish dish) {
                        DishDto dishDto = new DishDto();
                        Long categoryId = dish.getCategoryId();
                        Category category = categoryMapper.selectById(categoryId);
                        String categoryName = category.getName();
                        dishDto.setCategoryName(categoryName);
                        BeanUtils.copyProperties(dish, dishDto);
                        Long dishId = dish.getId();
                        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(dishId != null, DishFlavor::getDishId, dishId);
                        List<DishFlavor> dishFlavors = dishFlavorService.list(wrapper);
                        dishDto.setFlavors(dishFlavors);
                        list.add(dishDto);
                    }
                }
        );

        redisTemplate.opsForValue().set(key, list, 60, TimeUnit.MINUTES);
        return R.success(list);
    }


    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("{}", ids);
        dishService.removeWithFlavor(ids);
        return R.success("菜品删除成功");
    }
}

